/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.filter;

import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.dailydev.wave.robot.Robot;
import org.dailydev.wave.robot.context.IEventContext;

import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.RobotMessageBundle;

/**
 * <p>
 * {@link IFilter} implementation checking if {@link Event#getButtonName()}
 * equals to value specified in {@link ButtonPressed} annotation of a filtered
 * handler method. The filter FAILS only in case when {@link ButtonPressed}
 * annotation IS PRESENT on the method and it's <code>value</code> does NOT
 * EQUAL the value of {@link Event#getButtonName()}.
 * </p>
 * <p>
 * Note: The annotation and the filter are applicable only for event methods
 * serving {@link EventType#FORM_BUTTON_CLICKED} event type.
 * </p>
 * 
 * @see ButtonPressed
 * @author Roman Bosak, DailyDev.org
 */
public class ButtonPressedFilter implements IFilter {

    /**
     * {@link Robot}'s logger
     */
    private static Logger log = Logger.getLogger(ButtonPressedFilter.class.getName());

    /**
     * Checks if {@link Event#getButtonName()} equals to value specified in
     * {@link ButtonPressed} annotation of a filtered handler method.
     * 
     * @return <code>false</code> only in case when {@link ButtonPressed}
     *         annotation IS PRESENT on the <code>method</code> and it's
     *         <code>value</code> does NOT EQUAL the value of <code>event</code>
     *         's buttonName property. Otherwise returns <code>true</code>.
     */
    @Override
    public boolean filter(Method method, RobotMessageBundle bundle, Event event, IEventContext context) {
        ButtonPressed annotation = method.getAnnotation(ButtonPressed.class);
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Checks button name '" + event.getButtonName() + "' match with handler method annotation '"
                    + annotation + "'");
        }
        if (annotation != null) {
            String buttonName = annotation.value();
            return buttonName.equals(event.getButtonName());
        }
        return true;
    }

}
